package com.neusoft.demo11;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Manager {

    public void writeFile(List<Student> list) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter("student.txt");
            bw = new BufferedWriter(fw);
            //需要遍历List集合，获取学生的信息，之后将每个学生的信息写到student.txt
            //学号 姓名 性别 年龄 电话
            Iterator<Student> it =  list.iterator();
            while (it.hasNext()) {
                Student student = it.next();
                String str = student.getSid() + " " + student.getName() + " "
                        + student.getSex() + " " + student.getAge() + " "
                        + student.getPhone();
                //将以上字符串写到目标文件student.txt中
                bw.write(str);
                bw.newLine();// 换行
            }
            //关闭资源
            bw.close();
            fw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    public List<Student> readFile(String fileName) {
        FileReader fileReader = null;
        BufferedReader br = null;
        List<Student> list = new ArrayList<Student>();//创建一个容器
        try {
            fileReader = new FileReader(fileName); //节点流关联数据源
            br = new BufferedReader(fileReader); //处理流是对节点流功能的增强
            //读取文件
            String temp = null; //读取文件中的一行
            //temp (100 fender 男 12 1212121212)
            while ((temp = br.readLine()) != null) { //如果文件没有读完
                //1. 拆分字符串
                String[] s = temp.split(" ");
                Student student = new Student();
                student.setSid(Integer.parseInt(s[0]));
                student.setName(s[1]);
                student.setSex(s[2]);
                student.setAge(Integer.parseInt(s[3]));
                student.setPhone(s[4]);
                //将学生对象保存到List集合中
                list.add(student);
            }
            //关闭资源
            br.close();
            fileReader.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return list;
    }
}
